<html>
<body><canvas id="myCanvas" width="256" height="256"></canvas>
  <div id="log"></div>
</body>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script>

const t = async_test("CopyImageOnTransferredCanvas");

function main() {
  assert_true(!!window.testRunner, "This test requires window.testRunner.");

  if (window.testRunner) {
    initTest();
  } else {
    t.done();
  }
}

function initTest() {
  const canv = document.getElementById("myCanvas");
  const off = canv.transferControlToOffscreen();
  const ctx = off.getContext("2d");

  ctx.fillStyle = "#f00";
  ctx.fillRect(0, 0, 128, 128);
  ctx.fillStyle = "#0f0";
  ctx.fillRect(128, 0, 128, 128);
  ctx.fillStyle = "#00f";
  ctx.fillRect(0, 128, 128, 128);
  ctx.fillStyle = "#ff0";
  ctx.fillRect(128, 128, 128, 128);

  requestAnimationFrame(runTest);
}

function runTest() {
  // We need a frame barrier for the image frame to be propagated to the
  // placeholder canvas.
  requestAnimationFrame(() => {
    requestAnimationFrame(copyImage);
  });
}

function copyImage() {
  testRunner.copyImageThen(128, 128,
    t.step_func_done((width, height, snapshot) => {
      assert_equals(width, 256, "The copied image has a width of 256.");
      assert_equals(height, 256, "The copied image has a height of 256.");

      const data = new Uint8Array(snapshot);

      const pixelLeftTop = data.subarray(0, 4);
      assert_array_equals(pixelLeftTop, [255, 0, 0, 255],
        "The copied image's top left is red");

      const pixelRightTop = data.subarray(4 * 128, 4* 128 + 4);
      assert_array_equals(pixelRightTop, [0, 255, 0, 255],
        "The copied image's top right is green");

      const pixelLeftBottom = data.subarray(4 * 256 * 128, 4 * 256 * 128 + 4);
      assert_array_equals(pixelLeftBottom, [0, 0, 255, 255],
        "The copied image's bottom left is blue");

      const pixelRightBottom = data.subarray(4 * 256 * 128 + 4 * 128,
        4 * 256 * 128 + 4 * 128 + 4);
      assert_array_equals(pixelRightBottom, [255, 255, 0, 255],
        "The copied image's bottom right is yellow");
    }));
}

main();
  </script>
</html>
